<?php defined('SYSPATH') OR die('No direct access allowed.');

class Form_Register_Model extends Model{
	private $o_Post;
	private $a_FormContent;
	private $a_VerifySection;
	protected $db;
	
	public function __construct(){
		parent::__construct();
	}
	
	private function parse_data(){
		$this->o_Post = new Validation($_POST);
		
		$this->o_Post 	-> pre_filter( 'trim' )
      					-> pre_filter( 'htmlspecialchars' );
		
		$this->o_Post->add_rules('username', 'required');
		$this->o_Post->add_callbacks('username', array($this, '_unique_username'));
		$this->o_Post->add_rules('password', 'required');
		$this->o_Post->add_rules('password2', 'required');
		$this->o_Post->add_rules('password2', 'matches[password]');
		$this->o_Post->add_rules('reg', 'required');
		$this->o_Post->add_rules('email', 'required', 'valid::email');
		
		return $this->o_Post->validate();
	}
	public function _unique_username( $validator, $field ){
   		$login = $validator -> $field;
   		if( ORM :: factory( 'user' ) -> username_exists( $login ) )
      		$validator -> add_error( $field, 'user_exists' );
	}
	
	public function receive_data(){
		if ($this->parse_data()){
			$user = new User_Model;
			//1$this->a_FormContent = $_POST;
			$user ->load_data($this->o_Post ->as_array());
			
			if ($user->add(ORM :: factory('role', 'login') ) && $user ->save() ){
				$this->a_FormContent['info'] = Kohana :: lang ('register.successful');
			}
			else{
				$this->a_FormContent['info']= Kohana ::lang('register.error');
			}
			//Session:: instance() -> set_flash('flash', $msg);
			//url::redirect ('/');
		}
		else{
			//$this->template ->formRegister ->post = $this->o_Post;
			//$this->template -> formRegister ->errors = $this->o_Post->errors();
			$this->a_FormContent = $this->o_Post;
			$this->a_FormContent['errors'] = $this->o_Post->errors();
		}
		return $this->a_FormContent;
	}
}
?>